package net.pulseproject.router.debuggerapp;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.swing.SwingUtilities;

import net.pulseproject.commons.midi.DeviceLister;
import net.pulseproject.commons.midi.collection.DeviceFilter;
import net.pulseproject.commons.midi.entity.Device;
import net.pulseproject.commons.midi.entity.DeviceComparator;
import net.pulseproject.router.debuggerapp.view.MainWindow;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class RouterDebuggerApp implements Runnable {

	private static final Log LOG = LogFactory.getLog(RouterDebuggerApp.class);
	
	private final MainWindow window;
	
	private final DeviceLister deviceLister;
	
	public static void main(final String[] args) {
		LOG.info("Starting up application ...");
		
		final Injector injector = Guice.createInjector(new RouterDebuggerAppGuiceModule());
		final RouterDebuggerApp app = injector.getInstance(RouterDebuggerApp.class);
		app.startUp();
		
		LOG.info("Starting up application ... DONE");
	}
	
	@Inject
	public RouterDebuggerApp(final MainWindow window, final DeviceLister deviceLister) {
		this.window = window;
		this.deviceLister = deviceLister;
	}
	
	public final void startUp() {
		LOG.debug("startUp()");
		
		final Collection<Device> allDevices = this.deviceLister.listDevices();
		final DeviceFilter filter = new DeviceFilter();
		
		final Collection<Device> transmitterDevices = filter.filterTransmitting(allDevices);
		final List<Device> sortedTransmitterDevices = new LinkedList<Device>(transmitterDevices);
		Collections.sort(sortedTransmitterDevices, new DeviceComparator());
		
		final Collection<Device> receiverDevices = filter.filterReceiving(allDevices);
		final List<Device> sortedReceiverDevices = new LinkedList<Device>(receiverDevices);
		Collections.sort(sortedReceiverDevices, new DeviceComparator());
		
		this.window.startUp(sortedTransmitterDevices, sortedReceiverDevices);
		
		SwingUtilities.invokeLater(this);
	}

	@Override
	public final void run() {
		this.window.setVisible(true);
	}
}
